package org.ws.lifebacklog.event;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.ws.lifebacklog.util.Logger;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * @author sergey.valuy
 * 
 */
public class GenericBroadcastReceiver extends BroadcastReceiver {
	private Map<String, Set<GenericEvent>> listeners = new ConcurrentHashMap<String, Set<GenericEvent>>();

	/** {@inheritDoc} */
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getStringExtra(GenericEvent.KEY_EVENT_TYPE);

		Logger.i(getClass(), "onReceive with action " + action + "");
		Set<GenericEvent> actionListeners = listeners.get(action);
		if (actionListeners != null) {
			Logger.i(getClass(), "onReceive with action " + action + " and  with attached listenrs count "
					+ actionListeners.size());

			Iterator<GenericEvent> iter = actionListeners.iterator();
			while (iter.hasNext()) {
				GenericEvent event = iter.next();
				event.putExtras(intent);
				event.execute();
			}
		}
	}

	/**
	 * @param action
	 * @param event
	 */
	public void addEventListener(String action, GenericEvent event) {
		Logger.i(getClass(), "addEventListener for action " + action);
		Set<GenericEvent> actionListeners = listeners.get(action);
		if (actionListeners == null) {
			// TODO: fix to cuncurrent
			actionListeners = new HashSet<GenericEvent>();
		}
		actionListeners.add(event);
		listeners.put(action, actionListeners);
	}
}
